<template>
  <div v-if="member" class="bg-white p-6 rounded-lg flex flex-col h-full">

    <div class="flex items-center border-b border-gray-200 pb-4 mb-6">
      <n-button circle strong secondary @click="goBack" class="mr-4">
        <template #icon>
          <n-icon><arrow-back-outline /></n-icon>
        </template>
      </n-button>

      <n-divider vertical class="!h-8" />

      <span class="text-xl font-semibold ml-4">党员档案详情</span>

      <n-space align="center" class="ml-auto">
        <n-button @click="refreshMemberDetail" :loading="loading" quaternary circle>
          <template #icon>
            <n-icon><refresh-outline /></n-icon>
          </template>
        </n-button>
        <n-space align="center" class="text-sm text-gray-500">
          <n-icon :size="16"><person-outline /></n-icon>
          <span>姓名:</span>
          <span class="font-semibold text-gray-800">{{ member.memberName }}</span>
        </n-space>
        <n-divider vertical />
        <n-space align="center" class="text-sm text-gray-500">
          <n-icon :size="16"><school-outline /></n-icon>
          <span>学号:</span>
          <span class="font-semibold text-gray-800">{{ member.studentId }}</span>
        </n-space>
        <n-divider vertical />
        <n-space align="center" class="text-sm text-gray-500">
          <n-icon :size="16"><people-outline /></n-icon>
          <span>班级:</span>
          <span class="font-semibold text-gray-800">{{ member.studentClass }}</span>
        </n-space>
        <n-divider vertical />
        <n-space align="center" class="text-sm text-gray-500">
          <span>政治面貌:</span>
          <n-tag :type="statusType" size="small">{{ member.politicalStatus }}</n-tag>
        </n-space>
      </n-space>
    </div>

    <!-- 使用flex布局分为两列，等高 -->
    <div class="flex flex-1 min-h-0 gap-6">
      <!-- 左侧tab列 -->
      <div class="w-64 flex-shrink-0 flex flex-col">
        <div class="flex-1 overflow-y-auto">
          <div class="space-y-2 p-2">
            <div v-for="item in subMenuListWithValidation" :key="item.key" @click="activeTabKey = item.key" :class="[
              'flex items-center p-3 rounded-lg cursor-pointer transition-all duration-200',
              activeTabKey === item.key
                ? 'bg-blue-50 border-2 border-blue-200 text-blue-700'
                : 'bg-gray-50 border-2 border-transparent hover:bg-gray-100 text-gray-700'
            ]">
              <n-badge dot :show="shouldShowBadge(item.validation)" :type="getBadgeType(item.validation)"
                :processing="hasWarnings(item.validation)" class="flex-1">
                <span class="text-sm font-medium">{{ item.label }}</span>
              </n-badge>
              <div class="ml-2 flex items-center space-x-1">
                <n-tag v-if="getErrorCount(item.validation) > 0" type="error" size="tiny">
                  {{ getErrorCount(item.validation) }}
                </n-tag>
                <n-tag v-if="getInfoCount(item.validation) > 0" type="info" size="tiny">
                  {{ getInfoCount(item.validation) }}
                </n-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容列 -->
      <div class="flex-1 flex flex-col min-h-0">
        <!-- 验证信息区域 -->
        <div v-if="currentTabValidation && currentTabValidation.length > 0" class="mb-4 flex-shrink-0">
          <div class="space-y-2">
            <!-- 错误信息 -->
            <n-alert v-if="currentTabErrors.length > 0" type="error" :show-icon="true" closable>
              <template #icon>
                <n-icon><close-circle-outline /></n-icon>
              </template>
              <div class="space-y-1">
                <div class="font-medium">发现 {{ currentTabErrors.length }} 个错误：</div>
                <div class="space-y-1">
                  <div v-for="error in currentTabErrors" :key="error.key" class="text-sm">
                    • {{ error.message }}
                  </div>
                </div>
              </div>
            </n-alert>

            <!-- 信息提示 -->
            <n-alert v-if="currentTabInfos.length > 0" type="info" :show-icon="true" closable>
              <template #icon>
                <n-icon><information-circle-outline /></n-icon>
              </template>
              <div class="space-y-1">
                <div class="font-medium">{{ currentTabInfos.length }} 项未填写：</div>
                <div class="space-y-1">
                  <div v-for="info in currentTabInfos" :key="info.key" class="text-sm">
                    • {{ info.message }}
                  </div>
                </div>
              </div>
            </n-alert>

            <!-- 成功信息 -->
            <n-alert v-if="currentTabSuccesses.length > 0 && currentTabErrors.length === 0" type="success"
              :show-icon="true" closable>
              <template #icon>
                <n-icon><checkmark-circle-outline /></n-icon>
              </template>
              <div>
                所有已填写信息验证通过 ({{ currentTabSuccesses.length }} 项)
              </div>
            </n-alert>
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="flex-1 min-h-0 overflow-y-auto">
          <DocumentWrapper :title="currentTabLabel" @edit="openEditDrawer(currentTabItem)">
            <template #display>
              <!-- 特殊处理基本信息组件 -->
              <component 
                v-if="currentTabItem && activeTabKey === 'basicInfo'" 
                :is="currentTabItem.displayComponent" 
                :member="member"
                :basic-info="validationResults.basicInfo || []"
                :party-branch-history="validationResults.partyBranchHistory || []"
              />
              <!-- 其他组件使用 validation 属性 -->
              <component 
                v-else-if="currentTabItem" 
                :is="currentTabItem.displayComponent" 
                :member="member"
                :validation="currentTabItem.validation || []"
              />
            </template>
          </DocumentWrapper>
        </div>
      </div>
    </div>

    <n-drawer v-model:show="isDrawerActive" :width="800" placement="right" @close="handleDrawerClose">
      <n-drawer-content :title="`正在编辑：${editingItem?.label}`" closable>
        <!-- 编辑器组件也需要特殊处理 -->
        <component
          v-if="editingItem && activeTabKey === 'basicInfo'"
          :is="editingItem.editComponent"
          :member="member"
          :basic-info="validationResults.basicInfo || []"
          :party-branch-history="validationResults.partyBranchHistory || []"
          ref="editorRef"
          @save-basic-info="handleBasicInfoSave"
          @save-party-branch="handlePartyBranchSave"
          @delete-party-branch="handlePartyBranchDelete"
          @save-volunteer-activity="handleVolunteerActivitySave"
          @delete-volunteer-activity="handleVolunteerActivityDelete"
          @save-award="handleAwardSave"
          @delete-award="handleAwardDelete"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'activistAssessment'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @save-basic-info="handleActivistAssessmentBasicSave"
          @save-mentor="handleMentorSave"
          @delete-mentor="handleMentorDelete"
          @save-assessment-record="handleAssessmentRecordSave"
          @delete-assessment-record="handleAssessmentRecordDelete"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'activistThoughtReports'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @save-thought-report="handleActivistThoughtReportSave"
          @delete-thought-report="handleActivistThoughtReportDelete"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'externalInvestigations'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @save-external-investigation="handleExternalInvestigationSave"
          @delete-external-investigation="handleExternalInvestigationDelete"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'probationaryThoughtReports'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @save-probationary-thought-report="handleProbationaryThoughtReportSave"
          @delete-probationary-thought-report="handleProbationaryThoughtReportDelete"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'heartToHeartTalk'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'activistRecommendation'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'massOpinion'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'autobiography'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'comprehensiveReview'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'developmentTargetPrereview'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'applicationVolunteer'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'probationaryAcceptanceVoting'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'developmentPublicity'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'conversionApplication'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'conversionPublicity'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem && activeTabKey === 'conversionVotingSummary'"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
        <component
          v-else-if="editingItem"
          :is="editingItem.editComponent"
          :member="member"
          :validation="editingItem.validation || []"
          ref="editorRef"
          @auto-save="handleAutoSave"
        />
       
        <template #footer>
          <n-space justify="end" v-if="shouldShowSaveButton">
            <n-button @click="handleDrawerClose">取消</n-button>
            <n-button type="primary" @click="handleSave" :loading="saving">保存</n-button>
          </n-space>
          <n-space justify="end" v-else>
            <n-button @click="handleDrawerClose">关闭</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
  <div v-else class="flex items-center justify-center h-full">
    <n-spin size="large" />
    <span class="ml-4 text-gray-600">{{ loading ? '正在加载党员档案...' : '党员档案未找到' }}</span>
  </div>
</template>

<script setup>
import { defineAsyncComponent, computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  NSpace, NButton, NTabs, NTabPane, NTag, NIcon, NDivider, NAlert, NBadge,
  NDrawer, NDrawerContent, useMessage, useDialog, NSpin
} from 'naive-ui'
import DocumentWrapper from './DocumentWrapper.vue'
import { validateMember } from '@/utils/memberValidation.js'
import {
  fetchMemberDetail,
  updateMemberBasicInfo,
  updateApplicationDocs,
  updateActivistAssessment,
  updateApplicationVolunteer,
  updateProbationaryDocs,
  updateProbationaryAssessmentOpinion,
  createPartyBranchHistory,
  updatePartyBranchHistory,
  deletePartyBranchHistory,
  createVolunteerActivity,
  updateVolunteerActivity,
  deleteVolunteerActivity,
  createAward,
  updateAward,
  deleteAward,
  createMentor,
  updateMentor,
  deleteMentor,
  createAssessmentRecord,
  updateAssessmentRecord,
  deleteAssessmentRecord,
  createActivistThoughtReport,
  updateActivistThoughtReport,
  deleteActivistThoughtReport,
  createExternalInvestigation,
  updateExternalInvestigation,
  deleteExternalInvestigation,
  createProbationaryThoughtReport,
  updateProbationaryThoughtReport,
  deleteProbationaryThoughtReport
} from '@/api' // 导入API函数
import {
  ArrowBackOutline,
  PersonOutline,
  SchoolOutline,
  PeopleOutline,
  WarningOutline,
  CloseCircleOutline,
  InformationCircleOutline,
  CheckmarkCircleOutline,
  RefreshOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const props = defineProps({
  id: {
    type: String,
    required: true
  }
})

// 这个 ref 用于存储从 API 获取到的党员信息
const member = ref(null)
const loading = ref(false)
const saving = ref(false)

// 加载党员详情数据
const loadMemberDetail = async () => {
  loading.value = true
  try {
    const data = await fetchMemberDetail(props.id)
    member.value = data
  } catch (error) {
    console.error(`获取 ID 为 ${props.id} 的党员失败:`, error)
    const msg = error?.response?.message || error.message || '获取党员详情失败'
    message.error(msg)
    
    // 显示错误对话框，询问用户是否返回列表
    dialog.error({
      title: '获取党员详情失败',
      content: `无法获取党员详情，请稍后重试或返回列表页面。错误信息：${msg}`,
      positiveText: '返回列表',
      negativeText: '重试',
      onPositiveClick: () => {
        router.replace({ name: 'member-list' })
      },
      onNegativeClick: () => {
        loadMemberDetail()
      }
    })
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadMemberDetail()
})

const goBack = () => {
  router.back()
}

// 刷新党员详情数据
const refreshMemberDetail = async () => {
  await loadMemberDetail()
}

// 1. 【修改点】validationResults 现在依赖 member.value
const validationResults = computed(() => {
  // 增加保护判断，在 member 数据加载完成前返回空对象
  if (!member.value) {
    return {}
  }
  return validateMember(member.value)
})

// 当前活动tab的状态
const activeTabKey = ref('basicInfo')

// 2. 【修改点】statusType 现在依赖 member.value
const statusType = computed(() => {
  // 增加保护判断
  if (!member.value) {
    return 'default'
  }
  switch (member.value.politicalStatus) {
    case '正式党员': return 'success'
    case '预备党员': return 'warning'
    case '积极分子': return 'info'
    default: return 'default'
  }
})

// 基础的菜单配置 (这部分无需改动)

// 基础的菜单配置
const baseSubMenuList = [
  {
    key: 'basicInfo',
    label: '基本信息',
    displayComponent: defineAsyncComponent(() => import('./documents/BasicInfoDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/BasicInfoEditor.vue'))
  },
  {
    key: 'applicationForm',
    label: '入党申请书',
    displayComponent: defineAsyncComponent(() => import('./documents/ApplicationFormDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ApplicationFormEditor.vue'))
  },
  {
    key: 'heartToHeartTalk',
    label: '谈心谈话记录',
    displayComponent: defineAsyncComponent(() => import('./documents/HeartToHeartTalkDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/HeartToHeartTalkEditor.vue'))
  },
  {
    key: 'activistRecommendation',
    label: '积极分子推荐表',
    displayComponent: defineAsyncComponent(() => import('./documents/ActivistRecommendationDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ActivistRecommendationEditor.vue'))
  },
  {
    key: 'activistAssessment',
    label: '积极分子考察表',
    displayComponent: defineAsyncComponent(() => import('./documents/ActivistAssessmentDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ActivistAssessmentEditor.vue'))
  },
  {
    key: 'activistThoughtReports',
    label: '积极分子思想汇报',
    displayComponent: defineAsyncComponent(() => import('./documents/ActivistThoughtReportsDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ActivistThoughtReportsEditor.vue'))
  },
  {
    key: 'massOpinion',
    label: '群众意见',
    displayComponent: defineAsyncComponent(() => import('./documents/MassOpinionDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/MassOpinionEditor.vue'))
  },
  {
    key: 'autobiography',
    label: '自传',
    displayComponent: defineAsyncComponent(() => import('./documents/AutobiographyDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/AutobiographyEditor.vue'))
  },
  {
    key: 'externalInvestigations',
    label: '政审外调',
    displayComponent: defineAsyncComponent(() => import('./documents/ExternalInvestigationsDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ExternalInvestigationsEditor.vue'))
  },
  {
    key: 'comprehensiveReview',
    label: '政审综合',
    displayComponent: defineAsyncComponent(() => import('./documents/ComprehensiveReviewDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ComprehensiveReviewEditor.vue'))
  },
  {
    key: 'developmentTargetPrereview',
    label: '发展对象预审',
    displayComponent: defineAsyncComponent(() => import('./documents/DevelopmentTargetPrereviewDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/DevelopmentTargetPrereviewEditor.vue'))
  },
  {
    key: 'developmentPublicity',
    label: '发展党员公示结果',
    displayComponent: defineAsyncComponent(() => import('./documents/DevelopmentPublicityDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/DevelopmentPublicityEditor.vue'))
  },
  {
    key: 'applicationVolunteer',
    label: '入党志愿书',
    displayComponent: defineAsyncComponent(() => import('./documents/ApplicationVolunteerDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ApplicationVolunteerEditor.vue'))
  },
  {
    key: 'probationaryAcceptanceVoting',
    label: '接收预备党员表决汇总',
    displayComponent: defineAsyncComponent(() => import('./documents/ProbationaryAcceptanceVotingDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ProbationaryAcceptanceVotingEditor.vue'))
  },
  {
    key: 'probationaryAssessment',
    label: '预备党员考察表',
    displayComponent: defineAsyncComponent(() => import('./documents/ProbationaryAssessmentDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ProbationaryAssessmentEditor.vue'))
  },
  {
    key: 'probationaryThoughtReports',
    label: '预备期思想汇报',
    displayComponent: defineAsyncComponent(() => import('./documents/ProbationaryThoughtReportsDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ProbationaryThoughtReportsEditor.vue'))
  },
  {
    key: 'conversionApplication',
    label: '转正申请书',
    displayComponent: defineAsyncComponent(() => import('./documents/ConversionApplicationDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ConversionApplicationEditor.vue'))
  },
  {
    key: 'conversionPublicity',
    label: '预备党员转正公示结果',
    displayComponent: defineAsyncComponent(() => import('./documents/ConversionPublicityDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ConversionPublicityEditor.vue'))
  },
  {
    key: 'conversionVotingSummary',
    label: '预备党员转正表决汇总',
    displayComponent: defineAsyncComponent(() => import('./documents/ConversionVotingSummaryDisplay.vue')),
    editComponent: defineAsyncComponent(() => import('./documents/ConversionVotingSummaryEditor.vue'))
  }
];


// 将菜单和验证信息合并 (这部分无需改动，因为它依赖于已修复的 validationResults)
const subMenuListWithValidation = computed(() => {
  return baseSubMenuList.map(item => {
    let validation = validationResults.value[item.key] || []
    if (item.key === 'basicInfo') {
      const basicInfoValidation = validationResults.value.basicInfo || []
      const partyBranchValidation = validationResults.value.partyBranchHistory || []
      validation = [...basicInfoValidation, ...partyBranchValidation]
    }
    return { ...item, validation }
  })
})

// --- 之后的所有 computed 和 functions 都不需要修改 ---
// --- 因为它们都依赖于我们已经修复好的上层 computed 属性 ---

const currentTabItem = computed(() => {
  return subMenuListWithValidation.value.find(item => item.key === activeTabKey.value)
})

const currentTabValidation = computed(() => {
  return currentTabItem.value?.validation || []
})

const currentTabLabel = computed(() => {
  return currentTabItem.value?.label
})

const currentTabErrors = computed(() => {
  return currentTabValidation.value.filter(item => item.level === 'error')
})

const currentTabInfos = computed(() => {
  return currentTabValidation.value.filter(item => item.level === 'info')
})

const currentTabSuccesses = computed(() => {
  return currentTabValidation.value.filter(item => item.level === 'success')
})

const shouldShowBadge = (validation) => {
  if (!validation || !Array.isArray(validation)) return false
  return validation.some(item => ['error', 'info'].includes(item.level))
}

const getBadgeType = (validation) => {
  if (!validation || !Array.isArray(validation)) return 'default'
  const hasError = validation.some(item => item.level === 'error')
  const hasInfo = validation.some(item => item.level === 'info')
  if (hasError) return 'error'
  if (hasInfo) return 'warning'
  return 'success'
}

const hasWarnings = (validation) => {
  if (!validation || !Array.isArray(validation)) return false
  return validation.some(item => item.level === 'info') &&
    !validation.some(item => item.level === 'error')
}

const getErrorCount = (validation) => {
  if (!validation || !Array.isArray(validation)) return 0
  return validation.filter(item => item.level === 'error').length
}

const getInfoCount = (validation) => {
  if (!validation || !Array.isArray(validation)) return 0
  return validation.filter(item => item.level === 'info').length
}

// 判断是否应该显示保存按钮
const shouldShowSaveButton = computed(() => {
  // 只有这四个页面显示保存按钮，其他页面改为自动保存
  const saveButtonTabs = ['basicInfo', 'activistAssessment', 'externalInvestigations', 'probationaryAssessment']
  return saveButtonTabs.includes(activeTabKey.value)
})

// --- 编辑抽屉相关状态和逻辑 ---
const isDrawerActive = ref(false)
const editingItem = ref(null)
const editorRef = ref(null)

const openEditDrawer = (item) => {
  editingItem.value = item
  isDrawerActive.value = true
  
  // 对于不需要保存按钮的页面，设置自动保存
  if (!shouldShowSaveButton.value) {
    setupAutoSave()
  }
}

// 监听抽屉关闭，清除自动保存定时器
const handleDrawerClose = () => {
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
    autoSaveTimer = null
  }
  isDrawerActive.value = false
}

// 处理自动保存
const handleAutoSave = async () => {
  if (!editorRef.value || !member.value) return
  
  try {
    const updatedData = editorRef.value.getEditedData()
    if (!updatedData) return
    
    const memberId = member.value.memberId
    let result
    
    switch (activeTabKey.value) {
      case 'applicationForm':
      case 'heartToHeartTalk':
      case 'activistRecommendation':
      case 'massOpinion':
      case 'autobiography':
      case 'comprehensiveReview':
      case 'developmentTargetPrereview':
        // 入党相关档案更新
        let dataToSave = updatedData
        if (activeTabKey.value === 'heartToHeartTalk' && updatedData && updatedData.heartToHeartTalk) {
          dataToSave = updatedData.heartToHeartTalk
        }
        result = await updateApplicationDocs(memberId, activeTabKey.value, dataToSave)
        break
        
      case 'applicationVolunteer':
        // 入党志愿书更新
        result = await updateApplicationVolunteer(memberId, updatedData)
        break
        
      case 'probationaryAcceptanceVoting':
      case 'developmentPublicity':
      case 'conversionApplication':
      case 'conversionPublicity':
      case 'conversionVotingSummary':
        // 预备党员相关档案更新
        result = await updateProbationaryDocs(memberId, activeTabKey.value, updatedData)
        break
        
      default:
        // 其他类型的更新（如嵌套列表等）
        console.log(`自动保存 ${activeTabKey.value} 的数据`)
        return
    }
    
    // 重新加载数据
    await loadMemberDetail()
    message.success('自动保存成功', { duration: 2000 })
  } catch (error) {
    console.error('自动保存失败:', error)
    message.error('自动保存失败', { duration: 2000 })
  }
}

// 自动保存功能
let autoSaveTimer = null

const setupAutoSave = () => {
  if (!editorRef.value) return
  
  // 清除之前的定时器
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer)
  }
  
  // 设置新的防抖定时器
  autoSaveTimer = setTimeout(async () => {
    if (!editorRef.value || !member.value) return
    
    try {
      const updatedData = editorRef.value.getEditedData()
      if (!updatedData) return
      
      const memberId = member.value.memberId
      let result
      
      switch (activeTabKey.value) {
        case 'applicationForm':
        case 'heartToHeartTalk':
        case 'activistRecommendation':
        case 'massOpinion':
        case 'autobiography':
        case 'comprehensiveReview':
        case 'developmentTargetPrereview':
          // 入党相关档案更新
          let dataToSave = updatedData
          if (activeTabKey.value === 'heartToHeartTalk' && updatedData && updatedData.heartToHeartTalk) {
            dataToSave = updatedData.heartToHeartTalk
          }
          result = await updateApplicationDocs(memberId, activeTabKey.value, dataToSave)
          break
          
        case 'applicationVolunteer':
          // 入党志愿书更新
          result = await updateApplicationVolunteer(memberId, updatedData)
          break
          
        case 'probationaryAcceptanceVoting':
        case 'developmentPublicity':
        case 'conversionApplication':
        case 'conversionPublicity':
        case 'conversionVotingSummary':
          // 预备党员相关档案更新
          result = await updateProbationaryDocs(memberId, activeTabKey.value, updatedData)
          break
          
        default:
          // 其他类型的更新（如嵌套列表等）
          console.log(`自动保存 ${activeTabKey.value} 的数据`)
          return
      }
      
      // 重新加载数据
      await loadMemberDetail()
      message.success('自动保存成功', { duration: 2000 })
    } catch (error) {
      console.error('自动保存失败:', error)
      message.error('自动保存失败', { duration: 2000 })
    }
  }, 1000) // 增加防抖时间到1秒
}

// 保存编辑后的数据
const handleSave = async () => {
  if (!editorRef.value || !member.value) {
    message.error('编辑器未准备好或党员数据未加载')
    return
  }

  saving.value = true
  try {
    // 获取编辑后的数据
    const updatedData = editorRef.value.getEditedData()
    console.log('MemberDetail - handleSave - updatedData:', updatedData)
    console.log('MemberDetail - handleSave - activeTabKey:', activeTabKey.value)
    if (!updatedData) {
      message.error('未获取到编辑数据')
      return
    }

    // 根据当前编辑的选项类型调用不同的API
    let result
    const memberId = member.value.memberId

    switch (activeTabKey.value) {
      case 'basicInfo':
        // 基本信息更新
        result = await updateMemberBasicInfo(memberId, updatedData)
        break
        
      case 'applicationForm':
      case 'heartToHeartTalk':
      case 'activistRecommendation':
      case 'massOpinion':
      case 'autobiography':
      case 'comprehensiveReview':
      case 'developmentTargetPrereview':
        // 入党相关档案更新
        console.log('MemberDetail - handleSave - calling updateApplicationDocs with:', {
          memberId,
          documentType: activeTabKey.value,
          updatedData
        })
        
        // 确保heartToHeartTalk数据格式正确
        let dataToSave = updatedData
        if (activeTabKey.value === 'heartToHeartTalk' && updatedData && updatedData.heartToHeartTalk) {
          dataToSave = updatedData.heartToHeartTalk
          console.log('MemberDetail - heartToHeartTalk data to save:', dataToSave)
        }
        
        result = await updateApplicationDocs(memberId, activeTabKey.value, dataToSave)
        break
        
      case 'activistAssessment':
        // 积极分子考察表更新
        result = await updateActivistAssessment(memberId, updatedData)
        break
        
      case 'activistThoughtReports':
        // 积极分子思想汇报更新 - 使用组件自带的事件处理
        message.warning('请使用各记录的单独保存按钮进行保存')
        return
        
      case 'externalInvestigations':
        // 政审外调更新 - 使用组件自带的事件处理
        message.warning('请使用各记录的单独保存按钮进行保存')
        return
        
      case 'applicationVolunteer':
        // 入党志愿书更新
        result = await updateApplicationVolunteer(memberId, updatedData)
        break
        
      case 'probationaryThoughtReports':
        // 预备期思想汇报更新 - 使用组件自带的事件处理
        message.warning('请使用各记录的单独保存按钮进行保存')
        return
        
      case 'probationaryAssessment':
        // 预备党员考察表更新 - 特殊处理
        if (updatedData.probationaryAssessment && updatedData.probationaryAssessment.assessmentOpinions) {
          // 分别更新半年和一年考察意见
          const halfYearOpinion = updatedData.probationaryAssessment.assessmentOpinions[0];
          const fullYearOpinion = updatedData.probationaryAssessment.assessmentOpinions[1];
          
          // 更新半年考察意见
          if (halfYearOpinion) {
            await updateProbationaryAssessmentOpinion(memberId, 'half_year', halfYearOpinion);
          }
          
          // 更新一年考察意见
          if (fullYearOpinion) {
            await updateProbationaryAssessmentOpinion(memberId, 'full_year', fullYearOpinion);
          }
          
          result = { success: true };
        } else {
          throw new Error('预备党员考察表数据格式不正确');
        }
        break
        
      case 'probationaryAcceptanceVoting':
      case 'developmentPublicity':
      case 'conversionApplication':
      case 'conversionPublicity':
      case 'conversionVotingSummary':
        // 预备党员相关档案更新
        result = await updateProbationaryDocs(memberId, activeTabKey.value, updatedData)
        break
        
      default:
        // 其他类型的更新（如嵌套列表等）
        message.warning(`暂不支持 ${editingItem.value?.label} 的保存功能`)
        return
    }

    // 重新加载数据以确保显示最新信息
    await loadMemberDetail()
    
    // 关闭抽屉
    handleDrawerClose()
    
    // 提示用户保存成功
    message.success('保存成功！')
  } catch (error) {
    console.error('保存失败:', error)
    const msg = error?.response?.message || error.message || '保存失败，请重试'
    message.error(msg)
  } finally {
    saving.value = false
  }
}

// =============== 事件处理方法 ===============
// 处理基本信息保存
const handleBasicInfoSave = async (data) => {
  if (!member.value) return
  try {
    await updateMemberBasicInfo(member.value.memberId, data)
    await loadMemberDetail()
    message.success('基本信息保存成功')
  } catch (error) {
    console.error('保存基本信息失败:', error)
    message.error('保存基本信息失败')
  }
}

// 处理党支部历史保存
const handlePartyBranchSave = async (data, index) => {
  if (!member.value) return
  try {
    if (index === -1) {
      // 新增
      await createPartyBranchHistory(member.value.memberId, data)
    } else {
      // 更新
      await updatePartyBranchHistory(member.value.memberId, data.id, data)
    }
    await loadMemberDetail()
    message.success('党支部历史保存成功')
  } catch (error) {
    console.error('保存党支部历史失败:', error)
    message.error('保存党支部历史失败')
  }
}

// 处理党支部历史删除
const handlePartyBranchDelete = async (data, index) => {
  if (!member.value) return
  try {
    await deletePartyBranchHistory(member.value.memberId, data.id)
    await loadMemberDetail()
    message.success('党支部历史删除成功')
  } catch (error) {
    console.error('删除党支部历史失败:', error)
    message.error('删除党支部历史失败')
  }
}

// 处理志愿活动保存
const handleVolunteerActivitySave = async (data, index) => {
  if (!member.value) return
  try {
    if (index === -1) {
      // 新增
      await createVolunteerActivity(member.value.memberId, data)
    } else {
      // 更新
      await updateVolunteerActivity(member.value.memberId, data.id, data)
    }
    await loadMemberDetail()
    message.success('志愿活动保存成功')
  } catch (error) {
    console.error('保存志愿活动失败:', error)
    message.error('保存志愿活动失败')
  }
}

// 处理志愿活动删除
const handleVolunteerActivityDelete = async (data, index) => {
  if (!member.value) return
  try {
    await deleteVolunteerActivity(member.value.memberId, data.id)
    await loadMemberDetail()
    message.success('志愿活动删除成功')
  } catch (error) {
    console.error('删除志愿活动失败:', error)
    message.error('删除志愿活动失败')
  }
}

// 处理获奖记录保存
const handleAwardSave = async (data, index) => {
  if (!member.value) return
  try {
    if (index === -1) {
      // 新增
      await createAward(member.value.memberId, data)
    } else {
      // 更新
      await updateAward(member.value.memberId, data.id, data)
    }
    await loadMemberDetail()
    message.success('获奖记录保存成功')
  } catch (error) {
    console.error('保存获奖记录失败:', error)
    message.error('保存获奖记录失败')
  }
}

// 处理获奖记录删除
const handleAwardDelete = async (data, index) => {
  if (!member.value) return
  try {
    await deleteAward(member.value.memberId, data.id)
    await loadMemberDetail()
    message.success('获奖记录删除成功')
  } catch (error) {
    console.error('删除获奖记录失败:', error)
    message.error('删除获奖记录失败')
  }
}

// 处理积极分子考察表基本信息保存
const handleActivistAssessmentBasicSave = async (data) => {
  if (!member.value) return
  try {
    await updateActivistAssessment(member.value.memberId, data)
    await loadMemberDetail()
    message.success('积极分子考察表基本信息保存成功')
  } catch (error) {
    console.error('保存积极分子考察表基本信息失败:', error)
    message.error('保存积极分子考察表基本信息失败')
  }
}

// 处理培养人保存
const handleMentorSave = async (data, index) => {
  if (!member.value) return
  try {
    if (index === -1) {
      // 新增
      await createMentor(member.value.memberId, data)
    } else {
      // 更新
      await updateMentor(member.value.memberId, data.id, data)
    }
    await loadMemberDetail()
    message.success('培养人保存成功')
  } catch (error) {
    console.error('保存培养人失败:', error)
    message.error('保存培养人失败')
  }
}

// 处理培养人删除
const handleMentorDelete = async (data, index) => {
  if (!member.value) return
  try {
    await deleteMentor(member.value.memberId, data.id)
    await loadMemberDetail()
    message.success('培养人删除成功')
  } catch (error) {
    console.error('删除培养人失败:', error)
    message.error('删除培养人失败')
  }
}

// 处理考察记录保存
const handleAssessmentRecordSave = async (data, index) => {
  if (!member.value) return
  try {
    if (index === -1) {
      // 新增
      await createAssessmentRecord(member.value.memberId, data)
    } else {
      // 更新
      await updateAssessmentRecord(member.value.memberId, data.id, data)
    }
    await loadMemberDetail()
    message.success('考察记录保存成功')
  } catch (error) {
    console.error('保存考察记录失败:', error)
    message.error('保存考察记录失败')
  }
}

// 处理考察记录删除
const handleAssessmentRecordDelete = async (data, index) => {
  if (!member.value) return
  try {
    await deleteAssessmentRecord(member.value.memberId, data.id)
    await loadMemberDetail()
    message.success('考察记录删除成功')
  } catch (error) {
    console.error('删除考察记录失败:', error)
    message.error('删除考察记录失败')
  }
}

// 处理积极分子思想汇报保存
const handleActivistThoughtReportSave = async (data, index) => {
  if (!member.value) return
  try {
    if (index === -1) {
      // 新增
      await createActivistThoughtReport(member.value.memberId, data)
    } else {
      // 更新
      await updateActivistThoughtReport(member.value.memberId, data.id, data)
    }
    await loadMemberDetail()
    message.success('积极分子思想汇报保存成功')
  } catch (error) {
    console.error('保存积极分子思想汇报失败:', error)
    message.error('保存积极分子思想汇报失败')
  }
}

// 处理积极分子思想汇报删除
const handleActivistThoughtReportDelete = async (data, index) => {
  if (!member.value) return
  try {
    await deleteActivistThoughtReport(member.value.memberId, data.id)
    await loadMemberDetail()
    message.success('积极分子思想汇报删除成功')
  } catch (error) {
    console.error('删除积极分子思想汇报失败:', error)
    message.error('删除积极分子思想汇报失败')
  }
}

// 处理外调记录保存
const handleExternalInvestigationSave = async (data, index) => {
  if (!member.value) return
  try {
    if (index === -1) {
      // 新增
      await createExternalInvestigation(member.value.memberId, data)
    } else {
      // 更新
      await updateExternalInvestigation(member.value.memberId, data.id, data)
    }
    await loadMemberDetail()
    message.success('外调记录保存成功')
  } catch (error) {
    console.error('保存外调记录失败:', error)
    message.error('保存外调记录失败')
  }
}

// 处理外调记录删除
const handleExternalInvestigationDelete = async (data, index) => {
  if (!member.value) return
  try {
    await deleteExternalInvestigation(member.value.memberId, data.id)
    await loadMemberDetail()
    message.success('外调记录删除成功')
  } catch (error) {
    console.error('删除外调记录失败:', error)
    message.error('删除外调记录失败')
  }
}

// 处理预备期思想汇报保存
const handleProbationaryThoughtReportSave = async (data, index) => {
  if (!member.value) return
  try {
    if (index === -1) {
      // 新增
      await createProbationaryThoughtReport(member.value.memberId, data)
    } else {
      // 更新
      await updateProbationaryThoughtReport(member.value.memberId, data.id, data)
    }
    await loadMemberDetail()
    message.success('预备期思想汇报保存成功')
  } catch (error) {
    console.error('保存预备期思想汇报失败:', error)
    message.error('保存预备期思想汇报失败')
  }
}

// 处理预备期思想汇报删除
const handleProbationaryThoughtReportDelete = async (data, index) => {
  if (!member.value) return
  try {
    await deleteProbationaryThoughtReport(member.value.memberId, data.id)
    await loadMemberDetail()
    message.success('预备期思想汇报删除成功')
  } catch (error) {
    console.error('删除预备期思想汇报失败:', error)
    message.error('删除预备期思想汇报失败')
  }
}

// 暴露方法给父组件
defineExpose({
  refreshMemberDetail,
  loadMemberDetail
})
</script>